import type { Effect, Reducer } from 'umi';

import type { NoticeIconData } from '@/components/NoticeIcon';
import { queryNotices } from '@/services/user';
import type { ConnectState } from './connect.d';
import { queryI18nLanguage, searchMenuList } from '@/services/global';
import type { LanguageItem } from '@/components/SelectLang/typing';
import type { SystemMenuDataItem } from '@/system-typing';

export type NoticeItem = {
  id: string;
  type: string;
  status: string;
} & NoticeIconData;

export type GlobalModelState = {
  collapsed: boolean;
  notices: NoticeItem[];
  /**
   * 系统菜单列表
   */
  menuList: SystemMenuDataItem[];
  /**
   * 菜單数据是否已加载
   */
  menuLoaded: boolean;
  /**
   * 语言列表
   */
  languageList: LanguageItem[];
  /**
   * 当前是否需要加载i18n国际化资源
   */
  needLoadI18nData: boolean;
};

export type GlobalModelType = {
  namespace: 'global';
  state: GlobalModelState;
  effects: {
    searchMenuList: Effect;
    loadI18nData: Effect;
    fetchNotices: Effect;
    clearNotices: Effect;
    changeNoticeReadState: Effect;
  };
  reducers: {
    setMenuList: Reducer<GlobalModelState>;
    changeNeedLoadI18nData: Reducer<GlobalModelState>;
    changeLanguageList: Reducer<GlobalModelState>;
    changeLayoutCollapsed: Reducer<GlobalModelState>;
    saveNotices: Reducer<GlobalModelState>;
    saveClearedNotices: Reducer<GlobalModelState>;
  };
  subscriptions: { setup: any };
};

const GlobalModel: GlobalModelType = {
  namespace: 'global',

  state: {
    collapsed: false,
    notices: [],
    menuList: [],
    menuLoaded: false,
    languageList: [],
    needLoadI18nData: true
  },

  effects: {
    *searchMenuList(_, { put, call }) {
      const ajaxResp = yield call(searchMenuList);
      yield put({
        type: 'setMenuList',
        menuList: ajaxResp.resp
      });
    },
    *loadI18nData(_, { call, put, select }) {
      const needLoadI18nData = yield select((state: ConnectState) => state.global.needLoadI18nData);
      if (needLoadI18nData) {
        yield put({
          type: 'changeNeedLoadI18nData',
          needLoadI18nData: false
        });
        // 获取语言列表
        const data = yield call(queryI18nLanguage);
        yield put({
          type: 'changeLanguageList',
          languageList: data.resp
        });
      }
    },
    *fetchNotices(_, { call, put, select }) {
      const data = yield call(queryNotices);
      yield put({
        type: 'saveNotices',
        payload: data
      });
      const unreadCount: number = yield select(
        (state: ConnectState) => state.global.notices.filter((item) => !item.read).length
      );
      yield put({
        type: 'user/changeNotifyCount',
        payload: {
          totalCount: data.length,
          unreadCount
        }
      });
    },
    *clearNotices({ payload }, { put, select }) {
      yield put({
        type: 'saveClearedNotices',
        payload
      });
      const count: number = yield select((state: ConnectState) => state.global.notices.length);
      const unreadCount: number = yield select(
        (state: ConnectState) => state.global.notices.filter((item) => !item.read).length
      );
      yield put({
        type: 'user/changeNotifyCount',
        payload: {
          totalCount: count,
          unreadCount
        }
      });
    },
    *changeNoticeReadState({ payload }, { put, select }) {
      const notices: NoticeItem[] = yield select((state: ConnectState) =>
        state.global.notices.map((item) => {
          const notice = { ...item };
          if (notice.id === payload) {
            notice.read = true;
          }
          return notice;
        })
      );

      yield put({
        type: 'saveNotices',
        payload: notices
      });

      yield put({
        type: 'user/changeNotifyCount',
        payload: {
          totalCount: notices.length,
          unreadCount: notices.filter((item) => !item.read).length
        }
      });
    }
  },

  reducers: {
    setMenuList(state: any, { menuList }) {
      return { ...state, menuList, menuLoaded: true };
    },
    changeNeedLoadI18nData(state, { needLoadI18nData }): GlobalModelState {
      return { ...state, needLoadI18nData } as GlobalModelState;
    },
    changeLanguageList(state, { languageList }): GlobalModelState {
      return { ...state, languageList } as GlobalModelState;
    },
    changeLayoutCollapsed(state, { payload }): GlobalModelState {
      return {
        ...state,
        collapsed: payload
      } as GlobalModelState;
    },
    saveNotices(state, { payload }): GlobalModelState {
      return {
        collapsed: false,
        ...state,
        notices: payload
      } as GlobalModelState;
    },
    saveClearedNotices(state, { payload }): GlobalModelState {
      return {
        ...state,
        collapsed: false,
        // @ts-ignore
        notices: state.notices.filter((item): boolean => item.type !== payload)
      } as GlobalModelState;
    }
  },
  subscriptions: {
    setup({ dispatch, history }: { dispatch: any; history: any }): any {
      history.listen(() => {
        dispatch({
          type: 'loadI18nData'
        });
      });
    }
  }
};

export default GlobalModel;
